package es.onlysolutions.gs.web.controller;

import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import es.onlysolutions.arq.core.service.exception.ValidationException;
import es.onlysolutions.gs.web.commandBean.VideoBean;
import es.onlysolutions.gs.comm.entity.Video;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;

/**
 * Controller to view one of the video previously choose by the user.
 * This controller looks for an id of the entity or a YouTube ID passed directly.
 */
public class VideoController extends GSController
{

    /**
     * Param name for the id of the video.
     */
    public static final String REQUEST_VIDEO_PARAM = "v";

    /**
     * Param name for the youtube id.
     */
    public static final String REQUEST_YOUTUBE_ID_PARAM = "yid";

    protected AbstractCommandBean loadPage(HttpServletRequest httpServletRequest) throws Exception
    {
        return null;
    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object command, BindException bindException) throws Exception
    {
        VideoBean bean = (VideoBean) command;

        Long idVideo = ServletRequestUtils.getLongParameter( httpServletRequest, REQUEST_VIDEO_PARAM, -1 );
        String youTubeId = ServletRequestUtils.getStringParameter( httpServletRequest, REQUEST_YOUTUBE_ID_PARAM, "");

        Video video;
        if( idVideo != null && idVideo > 0 )
        {
            video = (Video) getFacade().load( Video.class, idVideo );
        }
        else if( youTubeId != null && youTubeId.length() > 0 )
        {
            video = new Video();
            video.setYouTubeId( youTubeId );
            video.setUser( getUserFromSession(httpServletRequest) );
        }
        else
        {
            ObjectError error = new ObjectError("aplication",new String[]{"video.idNotFoundInRequest"},
                    new String[]{REQUEST_VIDEO_PARAM, REQUEST_YOUTUBE_ID_PARAM},
                    "An ID for the video is needed under the {0} param or {1} param" );
            throw new ValidationException(error);
        }

        bean.setVideo( video );

        return new ModelAndView( getSuccessView(), getCommandName(), bean );
    }
}
